package com.dgut.cbd.finalexp.config;

import com.dgut.cbd.finalexp.service.UserService;
import com.dgut.cbd.finalexp.util.MyAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@Order(value = 99)
public class UserSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserService userService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                .antMatcher("/user/**")
                .authorizeRequests()
                .antMatchers("/user/register").permitAll()
                .anyRequest()
                .hasAnyAuthority("USER")
                .and()
                .formLogin()
                .loginPage("/user/login").permitAll()//放行登录请求入口
                .defaultSuccessUrl("/user/record")
                .and()
                .logout()
                .logoutUrl("/user/logout").permitAll()
                .logoutSuccessUrl("/user/login")
                .and()
                .csrf().disable()
                .exceptionHandling().accessDeniedHandler(new MyAccessDeniedHandler());
    }

}
